package com.shenrongrong.controller;
//文件存储
import com.shenrongrong.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
public class FileController {

    @RequestMapping("/upload")
    @ResponseBody
    public Result upload(MultipartFile file, HttpServletRequest request)throws IOException {
        // 把文件放在服务器目录：
        String realPath = request.getServletContext().getRealPath("/images/");
        System.out.println(realPath);

        File dir = new File("D:/images/");
        // 如果不存在则创建目录
        if (!dir.exists()) {
            dir.mkdir();
        }

        //获取文件的原始名字
        String fileName = System.currentTimeMillis()+"_"+file.getOriginalFilename();
        // 文件存储位置拼接：意味着：存储在D:/images/a.png
        File  newFile = new File(dir,fileName);
        //文件保存
        file.transferTo(newFile);
        System.out.println(newFile.getAbsolutePath());
        return Result.success("/images/"+fileName);
    }
}